<template>
  <div class="container">
    <el-row class="page">
      <el-col :span="16" align="left">
        <el-input v-model="data.params.constructionName" placeholder="工法名称" style="width: 150px; margin-right: 15px"
          clearable />
        <SelectOption :options="data.levelMethod" :placeholder="'工法级别'" @change-value="changeValue">
        </SelectOption>
        <SelectOption :options="data.MethodType" :placeholder="'工法类别'" @change-value="changeValue1">
        </SelectOption>
        <SelectOption :options="data.enterpriseRanking" :placeholder="'企业排名'" @change-value="changeValue2">
        </SelectOption>
        <el-button class="ordinary" @click="search()">搜索</el-button>
      </el-col>
      <el-col :span="8" align="right">
        <el-button class="unlock" @click="getUnlockBtn()" v-limit="'KJSL:HYBZHGX:JSGF:UNLOCK'">解锁</el-button>
        <el-button class="lock" @click="getLockBtn()" v-limit="'KJSL:HYBZHGX:JSGF:LOCK'">锁定</el-button>
        <el-button class="ordinary" @click="getExportBtn()" v-limit="'KJSL:HYBZHGX:JSGF:EXPERT'">批量导出</el-button>
        <el-button type="danger" @click="handleDetect()"  v-limit="'KJSL:HYBZHGX:JSGF:DELETE'">批量删除</el-button>
        <el-button type="primary" @click="handleAdd()" v-limit="'KJSL:HYBZHGX:JSGF:ADD'">新增</el-button>
      </el-col>
    </el-row>
    <div>


      <Table v-bind:loading="data.loading" :tableArr="data.allTableData" :pagination="data.page" :columns="data.columns" :total="data.page.total"
       @selectItem="getCurrentList" @delectTable="delectIds" @currentChange="currentChange" @sizeChange="sizeChange">
        <template #status="{ row }">
          <span v-if="row.isLock == 1">已锁定</span>
          <span v-else>
            <span style="color: #FFC783" v-if="row.status == '待确认'">待确认</span>
            <span style="color: #B5F1FF" v-if="row.status == '已确认'">已确定</span>
            <span style="color: #B5F1FF" v-if="row.status == '正常'">正常</span>
          </span>
        </template>
        <template #operate="{ row }">
          <el-button size="small" class="ordinary" v-show="row.updateFlag" :key="row.id + 'bj'" :disabled="row.isLock == 1"  v-limit="'KJSL:HYBZHGX:JSGF:EDIT'"
            @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" class="ordinary"  @click="handleDetail(row)">详情</el-button>
          <el-button v-if="row.status == '待确认'" size="small" type="primary" :key="row.id + 'qr'"  v-limit="'KJSL:HYBZHGX:JSGF:CONFIRM'"
            :disabled="row.isLock == 1" @click="handleConfirm(row)">确认</el-button>
        </template>
      </Table>

    </div>

    <!-- 弹窗 -->
    <el-dialog v-model="data.dialogVisible" width="60%" top="10vh" :show-close="false" :close-on-click-modal="false">
      <template #title>
        <div class="my-header" v-loading="data.detail_loading">
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane label="基本信息" name="1">
              <Information :selectArr="data.selectArr" ref="getAssociation" v-if="data.dialogVisible" :addFlag="data.addFlag"
                @valueFlag="valueFlag"></Information>
            </el-tab-pane>
            <el-tab-pane label="相关附件" name="5">
              <platformFiles :files="data.files" @dataChange="dataChange" @filesParams="filesParams" download="KJSL:HYBZHGX:JSGF:DOWNLOAD"  upload="KJSL:HYBZHGX:JSGF:UPLOAD" fileDelete="KJSL:HYBZHGX:JSGF:FILEDELETE"></platformFiles>
            </el-tab-pane>
            <el-tab-pane label="变更记录" name="6" v-if="data.addFlag == 1">
              <Record :changeLogs="data.changeLogs"></Record>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDialog">关闭</el-button>
          <el-button type="primary" @click="handleSave()">保存</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 弹窗 -->
    <el-dialog v-model="data.detailVisible" width="60%" top="10vh" :show-close="false" :close-on-click-modal="false">
      <template #title>
        <div class="my-header" v-loading="data.detailVisible_loading">
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane label="基本信息" name="1">
              <Informationxq :selectArr="data.selectArr" ref="getAssociation" v-if="data.detailVisible" :addFlag="data.addFlag"
                @valueFlag="valueFlag"></Informationxq>
            </el-tab-pane>
            <el-tab-pane label="相关附件" name="5">
              <platformFilesxq :files="data.files" @dataChange="dataChange" @filesParams="filesParams" download="KJSL:HYBZHGX:JSGF:DOWNLOAD"  upload="KJSL:HYBZHGX:JSGF:UPLOAD" fileDelete="KJSL:HYBZHGX:JSGF:FILEDELETE"></platformFilesxq>
            </el-tab-pane>
            <el-tab-pane label="变更记录" name="6" v-if="data.addFlag == 1">
              <Record :changeLogs="data.changeLogs"></Record>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">关闭</el-button>
<!--          <el-button type="primary" @click="handleSave()">保存</el-button>-->
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import platformFiles from '@/views/science/components/platformFiles/platformFiles.vue'
import platformFilesxq from '@/views/science/components/platformFiles/platformFilesxq.vue'
import Record from "@/views/science/components/record/record.vue"
import SelectOption from '@/views/science/components/selectOption/index.vue'
import Table from '@/views/science/components/table/TableDate.vue'
import { onMounted, reactive, ref } from 'vue'
import Information from './information.vue'
import Informationxq from './informationxq.vue'
import tableData from './tableHeader.json'
// import record from '@/views/science/components/record/record.vue'
import * as proxy from '@/constants/proxy'
import request from '@/utils/request'
import { Modals, tips } from '@/views/science/components/tips/tips'
// import { validatePhoneNumber } from '@/utils/util'
import { ElMessage } from 'element-plus'
import { useStore } from 'vuex'
import {
getAdd,
getConfirm,
getDelect,
getDetail,
getExport,
getList,
getLock,
getUnlock,
getUpdate,
} from '../../api/technicalMethod'
export default {
  name: 'technicalNorms',
  components: {
    SelectOption,
    Table,
    Information,
    Informationxq,
    platformFiles,
    platformFilesxq,
    Record,
  },
  setup() {
    const store = useStore()
    const activeName = ref('1')
    const data = reactive({
      selectArr: [] as any,
      addFlag: 0,
      unit: [],
      dialogVisible: false,
      recordShow: false,
      loading: false,
      detail_loading:false,
      page: { page: 1, limit: 10, total: 0 },
      fileList: [],
      changeLogs: [],
      id: '',
      params: {
        constructionName: '',
        levelName: '',
        normType: '',
        trdClass: '',
        trdLevelId: '',
        trdClassId: '',
        mainUnit: '',
        enterpriseRankingId: '',
        current: 1,
        size: 10,
      },
      // 字典
      levelMethod: [],
      MethodType: [],
      enterpriseRanking: [],

      typeValue: '',
      information: [],
      selectedRows: [] as any,
      columns: tableData.platformTableHeader,
      ids: [],
      files: [],
      allTableData: [],
      flag: null,
      detailVisible_loading:false,
      detailVisible: false,
    })
    //详情数据获取
    const detailVisibleData = async (id) => {
      data.detailVisible_loading = true
      data.detailVisible = true
      let res = await getDetail(id)
      if (res.data.success) {
        // 主要完成人----数组格式
        res.data.data.info.mainCompletePersonIds = res.data.data.info.mainCompletePersonIds.split(',')
        res.data.data.info.mainCompletePersons = res.data.data.info.mainCompletePersons.split(',')
        data.selectArr = convertToObjects(res.data.data.info.mainCompletePersonIds,res.data.data.info.mainCompletePersons);
        store.commit('technicalNorms/getMethodForm', { ...res.data.data.info })
        data.files = res.data.data.files
        data.changeLogs = res.data.data.operLog
        data.detailVisible_loading = false
      }else{
        data.detailVisible_loading = false
      }

    }
    // 记录点击后的id
    let rowId: string | null;
    const handleDetail = (row) => {
      rowId = row.id;
      store.commit('technicalNorms/getMethodRowId', row.id)
      data.addFlag = 1
      detailVisibleData(row.id)
    }

    const handleClose = () => {
      data.detailVisible = false
      data.recordShow = false
      activeName.value = '1'
      store.commit('technicalNorms/emptyMethodForm')
    }


    interface MyObject {
      userId: string;
      cname: string;
    }
    // 字典
    const affiliation = () => {
      request({
        url: proxy.CHECC_API_CMS + '/dictItem/codelist',
        method: 'post',
        data: ['KJSL_CONSTRUCTION_METHOD_LEVEL_CATEGORY', 'KJSL_ENTERPRISE_RANKING'],
      }).then((res) => {
        data.levelMethod = res.data.data.KJSL_CONSTRUCTION_METHOD_LEVEL_CATEGORY
        data.enterpriseRanking = res.data.data.KJSL_ENTERPRISE_RANKING
      })
    }

    // 回调分页的功能
    const currentChange = (current) => {
      data.params.current = current

      tableList()
    }

    const sizeChange = (size) => {
      data.params.size = size
      tableList()
    }

    const search = () => {
      tableList()
    }
    //搜索change
    const changeValue = (item) => {
      data.params.trdClassId = ''
      data.typeValue = ''

      if (item) {
        data.params.trdLevelId = item.itemValue
      } else {
        data.params.trdLevelId = ''
      }
      data.MethodType = item.children
      data.params.trdClassId = ''
      data.typeValue = ''
    }
    const changeValue1 = (item) => {
      data.params.trdClassId = item.itemValue
      data.typeValue = item.itemText
    }
    const changeValue2 = (item) => (data.params.enterpriseRankingId = item.itemValue)
    const getCurrentList = (currentList) => {
      console.log(currentList, 'getCurrentList')
      data.selectedRows = currentList
    }
    const delectIds = (ids) => {
      data.id = ids
      data.ids = ids
    }
    //主页面表格初始化
    const tableList = async () => {
      data.loading = true
      let params = data.params
      data.id = ''

      let res = await getList(params)
      if (res.data.success) {
        let records = res.data.data
        records.records.map((item) => {
          if (item.status == 0) {
            item.status = '待确认'
          } else {
            item.status = '已确认'
          }
        })
        data.allTableData = res.data.data.records
        data.page.total = records.total
        data.loading = false
      }else{
        data.loading = false
      }
    }

    //详情数据获取
    const detailData = async (id) => {
      data.detail_loading = true
      data.dialogVisible = true

      let res = await getDetail(id)
      if (res.data.success) {
        const arr = res.data.data.info
        // 主要完成人----数组格式
        res.data.data.info.mainCompletePersonIds = res.data.data.info.mainCompletePersonIds.split(',')
        res.data.data.info.mainCompletePersons = res.data.data.info.mainCompletePersons.split(',')
        data.selectArr = convertToObjects(res.data.data.info.mainCompletePersonIds,res.data.data.info.mainCompletePersons);
        store.commit('technicalNorms/getMethodForm', { ...arr })
        data.files = res.data.data.files
        data.changeLogs = res.data.data.operLog
        data.detail_loading = false
      }else{
        data.detail_loading = false
      }
    }

    const convertToObjects = (arr1: string[], arr2: string[]): MyObject[] => {
      const objectArray: MyObject[] = [];
      for (let i = 0; i < arr1.length; i++) {
        const obj: MyObject = {
          userId: arr1[i],
          cname: arr2[i]
        };
        objectArray.push(obj);
      }

      return objectArray;
    };
    //解锁
    const getUnlockBtn = () => {
      if (data.id.length==1) {
        Modals('是否解锁选择内容', '提示', 'warning')
          .then(async () => {
            let res = await getUnlock(data.id)
            if (res.data.success) {
              tips('解锁成功', 'success')
              tableList()
            }
          })
          .catch(() => {
            console.log('点击了取消')
          })
      } else {
        tips('请选择', 'warning')
      }
    }
    //锁定
    const getLockBtn = () => {
      if (data.id.length==1) {
        let flag = true
        console.log(data.selectedRows, 'selectedRows')
        data.selectedRows.forEach((obj) => {
          if (obj.status == '待确认') {
            flag = false
          }
        })
        if (!flag) {
          ElMessage({
            message: '请确认后再进行锁定',
            type: 'warning',
          })
          return
        }
        Modals('是否锁定选择内容', '提示', 'warning')
          .then(async () => {
            let res = await getLock(data.id)
            console.log(data.id)
            if (res.data.success) {
              tips('锁定成功', 'success')
              tableList()
            }
          })
          .catch(() => {
            console.log('点击了取消')
          })
      } else {
        tips('请选择一条数据', 'warning')
      }
    }
    //批量导出
    const getExportBtn = async () => {
      let msg = '是否导出全部数据'
      if(data.ids.length>0){
        msg = '是否导出所选数据'
      }
      Modals(msg, "提示", "warning")
          .then(async () => {
            const params = {
              ...data.params,
              ids: data.ids
            }
          await getExport(params, '技术工法')
        })
        .catch(() => {
          console.log('点击了取消')
        })

      // await getExport(data.params);
    }
    //批量删除
    const handleDetect = () => {
      // if (data.id) {
        Modals('是否删除选择内容', '提示', 'warning')
          .then(async () => {
            let res = await getDelect(data.id)
            if (res.data.success) {
              tips('删除成功', 'success')
              tableList()
            }
          })
          .catch(() => {
            console.log('点击了取消')
          })
      // } else {
      //   tips('请选择', 'warning')
      // }
    }

    // 新增
    const handleAdd = () => {
      data.dialogVisible = true
      data.addFlag = 0
      data.files = []
      rowId = null;
      store.commit('technicalNorms/emptyMethodForm')
    }


    //编辑
    const handleEdit = (row) => {
      detailData(row.id)
      store.commit('technicalNorms/getMethodRowId', row.id)
      rowId = row.id;
      data.addFlag = 1
    }

    const valueFlag = (flag) => {
      data.flag = flag
    }

    const handleConfirm = (row) => {
      Modals('是否确认当前流程', '提示', 'warning')
        .then(async () => {
          let res = await getConfirm({ id: row.id })
          if (res.data.success) {
            tableList()
          }
        })
        .catch(() => {
          console.log('点击了取消')
        })
    } //查看
    // 关闭
    const handleCloseDialog = () => {
      data.dialogVisible = false
      data.recordShow = false
      activeName.value = '1'
      store.commit('technicalNorms/emptyMethodForm')
    }

    //从state获取form 表单的数据.同时检验基本信息的检验
    const getAssociation = ref()

    const handleSave = async () => {
      const form = Object.assign({}, store.state.technicalNorms.methodForm)
      if(Array.isArray(form.mainCompletePersonIds) && form.mainCompletePersonIds.length>0){
           form.mainCompletePersonIds = form.mainCompletePersonIds.join(',')
           form.mainCompletePersons = form.mainCompletePersons.join(',')
      }

      getAssociation.value.submitForm()

      if (!data.flag) {
        return tips('请将基本信息补充完整', 'warning')
      }

      const params = {
        info: form,
        files: data.files,
      }

      activeName.value = '1'

      // 通过返回值判断
      let res

      if (data.addFlag == 0) {
        delete form.id
        res = await getAdd(params)
      } else {
        form.id = rowId;
        res = await getUpdate(params)
      }

      if (res.data.success) {
        ElMessage.success('操作成功')

        data.dialogVisible = false

        activeName.value = '1'
        store.commit('technicalNorms/emptyMethodForm')
        tableList()
      }

    }

    // 弹窗打开改变
    const dataChange = () => {
      detailData(store.state.technicalNorms.methodRowId)
    }

    const filesParams = (params) => {
      data.files = params
    }


    tableList()
    onMounted(() => {
      affiliation()
    })
    return {
      store,
      activeName,
      data,
      getAssociation,
      currentChange,
      sizeChange,
      handleAdd,
      dataChange,
      filesParams,
      tableList,
      getCurrentList,
      delectIds,
      changeValue,
      changeValue1,
      changeValue2,
      search,
      getUnlockBtn,
      getLockBtn,
      getExportBtn,
      handleDetect,
      handleEdit,
      handleConfirm,
      handleCloseDialog,
      handleSave,
      detailData,
      affiliation,
      valueFlag,
      convertToObjects,
      handleDetail, //详情
      handleClose, //详情
    }
  },
}
</script>

<style scoped lang="scss">
.container {
  background-color: white;
  padding: 20px;
}

// :deep(.el-dialog__body) {
//   padding: 0 !important
// }
:global(.el-dialog__body) {
  padding: 0;
}

.dialogCloseBtn {
  position: absolute;
  top: 20px;
  right: 20px;
}

// .el-col {
//   line-height: 60px;
// }

.pageName {
  font-weight: 700;
}

.el-form-item {
  .el-input {
    width: 100px;
  }

  .el-select {
    width: 100px;
  }
}

:deep(.demo-tabs > .el-tabs__content) {
  max-height: 500px;
  overflow-y: scroll;
  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* IE 10+ */
}

:deep(.demo-tabs > .el-tabs__content::-webkit-scrollbar) {
  display: none;
  /* Chrome Safari */
}
</style>
